package com.product.shopping.Rabbit;

import com.product.shopping.config.RabbitConfig;
import com.product.shopping.config.RedisService;
import com.product.shopping.dao.ProductDao;
import com.product.shopping.entity.Product;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.impl.AMQImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 一个生产者，一个消费者
 */
@Component
@RabbitListener(queues = RabbitConfig.QUEUE_A)
public class MsgReceiver {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    RedisService redisStringUtils;
    @Resource
    ProductDao productDao;
    @Autowired
    private RedisTemplate redisTemplate;



    int i = 0;


    @RabbitHandler
    public void process(Channel channel, String content) {
        logger.info(">>>>>>>>>>>>>>>>>接收到秒杀请求，商品ID为："+content+"检查Redis中库存是否为0");
        try {
            Long num = redisTemplate.opsForValue().decrement(content);
            if(num < 0) {
                /**
                 * 此处不能判断等于0，因为当商品库存为1时，Redis执行递减返回为0
                 * 如果判断为0商品最后不能卖完也就是当库存为1时此处就抛异常了
                 */
                throw new ServerBizException(ErrorCodeEnum.PRODUCT_INVENTORY_IS_NULL);
            }
            logger.info("接收时>>>>>>>>>>>"+num);
            Map map = new HashMap<>();
            map.put("Pid", content);
            map.put("Pnum", num);
            //根据商品的id和库存同步数据到MySQL
            if(productDao.updateQuantityByPid(map) == 0) {
                throw new ServerBizException("同步到商品表异常！");
            }
            //channel.basicAck(Long.parseLong(content),true);
        } catch (Exception | ServerBizException e) {
            e.printStackTrace();
        }
    }

}

